package com.saianfu.flowable.demo.common.impl

import com.saianfu.flowable.demo.common.ActInstanceQuery
import org.flowable.engine.RepositoryService
import org.flowable.engine.RuntimeService
import org.flowable.engine.TaskService
import org.flowable.engine.runtime.ProcessInstance
import org.flowable.engine.runtime.ProcessInstanceQuery
import org.flowable.task.api.Task
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

/**
 * 流程实例查询
 *
 */
@Component
class InstanceQueryHandler :  ActInstanceQuery {

    @Autowired
    lateinit var runtimeService: RuntimeService

    @Autowired
    lateinit var taskService: TaskService

    override fun createProcessInstanceQuery(): ProcessInstanceQuery {
        return runtimeService.createProcessInstanceQuery()
    }

    override fun processInstanceId(processInstanceId: String): ProcessInstance {
        return createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult()
    }

    override fun processInstanceBusinessKey(processInstanceBusinessKey: String): ProcessInstance {
        return createProcessInstanceQuery().processInstanceBusinessKey(processInstanceBusinessKey).singleResult()
    }

    override fun hasProcessInstanceFinished(processInstanceId: String): Boolean {
        val pi = processInstanceId(processInstanceId)
        return pi == null
    }

    override fun taskId(taskId: String): ProcessInstance {
        val task: Task = taskService.createTaskQuery().taskId(taskId).singleResult()
        val processInstId = task.processInstanceId
        return processInstanceId(processInstId)
    }

    companion object {
        protected var logger = LoggerFactory.getLogger(InstanceQueryHandler::class.java)
    }
}